import { baseUrl } from '@/config'
import { getToken } from './auth'

export const request = async (options) => {
  try {
    // 获取token并添加到请求头
    const token = getToken()
    const headers = {
      ...options.header,
      'content-type': 'application/json'
    }

    if (token) {
      headers['Authorization'] = `Bearer ${token}`
    }

    const res = await uni.request({
      url: baseUrl + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: headers
    })

    console.log("data", res)

    // 处理未授权的情况
    if (res.statusCode === 401) {
      // 清除token
      uni.removeStorageSync('token')
      // 跳转到登录页
      uni.reLaunch({
        url: '/pages/login/login'
      })
      throw new Error('登录已过期，请重新登录')
    }

    if (res.statusCode === 200) {
      if (res.data.code === 200) {
        return res.data.data
      } else {
        throw new Error(res.data?.message || '请求失败')
      }
    } else {
      throw new Error(res.data?.message || '请求失败')
    }
  } catch (err) {
    console.error('API请求错误:', err)
    throw err
  }
}

// 用户登录
export const login = async (data) => {
  return request({
    url: '/api/v1/users/login',
    method: 'POST',
    data
  })
}

// 用户注册
export const register = async (data) => {
  return request({
    url: '/api/v1/users/register',
    method: 'POST',
    data
  })
}

// 获取视频列表
export const getVideoList = async (params) => {
  return request({
    url: '/api/v1/videos',
    method: 'GET',
    timeout: 6000000,
    data: params
  })
}

// 记录观看历史
export const recordWatchHistory = async (videoID) => {
  return request({
    url: '/api/v1/videos/watch',
    method: 'POST',
    data: { videoID }
  })
}

// 上传图片文件
export const uploadImageFile = async (options) => {
  try {
    const token = getToken()

    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: baseUrl + '/api/v1/images/batch',
        filePath: options.imagePath,
        name: "images",
        async: true,
        crossDomain: true,
        method: "POST",
        processData: false,
        contentType: false,
        timeout: 6000000,
        formData: {
          title: options.imageTitle,
          description: options.imageDescription,
          //tags: "tag1,tag2"
        },
        header: {
          'Authorization': token ? `Bearer ${token}` : '',
        },
        // 添加进度更新回调
        onProgressUpdate: (res) => {
          if (options.onProgressUpdate) {
            options.onProgressUpdate(res.progress)
          }
        },
        success: (uploadFileRes) => {
          try {
            const data = JSON.parse(uploadFileRes.data)
            if (uploadFileRes.statusCode === 200) {
              if (data.code === 200) {
                resolve(data.data)
              } else {
                reject(new Error(data?.message || '图片上传失败'))
              }
            } else {
              reject(new Error(data?.message || '图片上传失败'))
            }
          } catch (e) {
            reject(new Error('服务器返回数据格式错误'))
          }
        },
        fail: (err) => {
          reject(new Error(err.errMsg || '网络请求失败'))
        }
      })
    })
  } catch (error) {
    throw error
  }
}

// 获取图片列表
export const getImageList = async (params) => {
  return request({
    url: '/api/v1/images',
    method: 'GET',
    data: params
  })
}

// 上传视频文件
export const uploadVideoFile = async (options) => {
  try {
    const token = getToken()

    return new Promise((resolve, reject) => {
     const uploadTask = uni.uploadFile({
        url: baseUrl + '/api/v1/videos/fast',
        filePath: options.videoPath,
        name: "video",
        async: true,
        crossDomain: true,
        method: "POST",
        processData: false,
        contentType: false,
        timeout: 6000000,
        formData: {
    //      video: options.fileName,
          category_id: 1,
          title: options.videoTitle,
          description: options.videoDescription,
          tags: "tag1,tag2"
        },
        header: {
          'Authorization': token ? `Bearer ${token}` : '',
        },
     
        success: (uploadFileRes) => {
          try {
            const data = JSON.parse(uploadFileRes.data)
            if (uploadFileRes.statusCode === 200) {
              if (data.code === 200) {
                resolve(data.data)
              } else {
                reject(new Error(data?.message || '视频上传失败'))
              }
            } else {
              reject(new Error(data?.message || '视频上传失败'))
            }
          } catch (e) {
            reject(new Error('服务器返回数据格式错误'))
          }
        },
        fail: (err) => {
          console.error('视频上传失败:', err)
          reject(new Error('网络错误，请检查网络连接后重试'))
        }
      })

      // 监听上传进度
      uploadTask.onProgressUpdate((res) => {
        if (options.onProgressUpdate) {
          options.onProgressUpdate(res.progress)
        }
      })
    })
  } catch (err) {
    console.error('视频上传API错误:', err)
    throw err
  }
}

// 更新用户信息
export const updateUserInfo = async (data) => {
  return request({
    url: '/api/v1/users/info',
    method: 'PUT',
    data
  })
}